function script_generation_DB
list = dir('C:\Users\Ernest\Documents\DB_dcm');
DB = fopen('C:\Users\Ernest\Documents\MATLAB\icem\DB\DB.txt','w');
for i=3:length(list)
 i
    filePath=['C:\Users\Ernest\Documents\DB_dcm\' list(i).name];
   % if ~exist(folderPath)
    %    folderPath=['E:\normal PET DB final\DICOM\' list(i).name '\TEP10'];
    %end
    fileName = UnsliceDicom(filePath);
    fprintf(DB,'%s\t%s\tsain\r\n',fileName,fileName(23:24));
end
fclose(DB);
normalizesw();
end


function fileName = UnsliceDicom( filePath) %folderPath )
% Read every .IMA file in the input folder, create a new niftii file
% and put it in the same folder, returns the path to the file.
%sliceFiles = dir(fullfile(folderPath,'*.IMA'));
%sliceFiles = [sliceFiles dir(fullfile(folderPath,'*.dcm'))];
%info=dicominfo(fullfile(folderPath,sliceFiles(1).name));
info=dicominfo(filePath);
%fileNames = cell(1,length(sliceFiles));
%headers = [];
%for i=1:length(sliceFiles)
 %   fileNames{i} = fullfile(folderPath,sliceFiles(i).name);
%end
%fp{1} = filePath;
% headers = icem_spm_dicom_headers(fp);
% headers{1}.Modality = 'PT';
% newFile = spm_dicom_convert(headers,'all','flat','nii');
% newFile = newFile.files{1};
% [pathstr, name, ext] = fileparts(newFile);
% copyfile(newFile, fullfile('C:\Users\Ernest\Documents\DB_temp',[name ext]));
% newFile = fullfile('C:\Users\Ernest\Documents\DB_temp',[name ext]);
% header = spm_vol(newFile);
% vol = spm_read_vols(header);
% header.mat(1:3,4) = zeros(1,3);
% header.mat(:,4) = -(header.mat*[(header.dim/2)';-1]);
% spm_write_vol(header,vol);    
%
mc = 'C:\Users\Ernest\Documents\Matlab\icem\XMedCon\bin\medcon.exe';


familyName=info.PatientName.FamilyName;
firstName=info.PatientName.GivenName;
age=sscanf(info.PatientAge, '%dY');
birthDate=info.PatientBirthDate;
acquisitionDate=info.AcquisitionDate;
sex=info.PatientSex;
studyTime=strcat(info.StudyTime(1:2),'h',info.StudyTime(3:4));

%replace '.' and ' ' with '_'
familyName = regexprep(familyName, '[ .]', '_');
familyName = fixedLength(familyName, 3, '_');
firstName = regexprep(firstName, '[ .]', '_');
firstName = fixedLength(firstName, 2, '_');
% Building name for the new NIfTI file:
newNIfTI=strcat(familyName,'_', firstName, '_', acquisitionDate, '_', ...
    studyTime, '_', num2str(age));
% Creating full path for the new NIfTI :

% name of the new folder where NIfTI files are created :
destFolder = fullfile('C:\Users\Ernest\Documents\MATLAB\icem\DB\',strcat(familyName, '_', firstName));
if ~exist(destFolder, 'dir')
    mkdir(destFolder); % creating destination folder
end
% not saving DICOM header in the destination folder
%save(fullfile(destFolder,['header' newNIfTI '.mat']),'info');
NIfTIPath = fullfile(destFolder, [newNIfTI '.nii']);

system([mc ' -f "' filePath '" -c nifti -o ' NIfTIPath])
%fileName = ['sw' newNIfTI];
%movefile(newFile,NIfTIPath);
fileName = newNIfTI;
end


function normalizesw()
DB = 'C:\Users\Ernest\Documents\MATLAB\icem\DB'
folders = dir(DB)
for i=3:length(folders)
    if exist(fullfile(DB,folders(i).name),'dir')
        PetPathFolder = fullfile(DB,folders(i).name);
        petName = dir(PetPathFolder);
        petName = petName(3).name
        %movefile(fullfile(PetPathFolder,petName),fullfile(PetPathFolder,petName(3:end)))
        %PETPath = fullfile(PetPathFolder,petName(3:end))
        PETPath = fullfile(PetPathFolder,petName)
        
        [pathstr, name, ext] = fileparts(PETPath);% .nii neither normalised nor smoothed
        % Normalise.
        wPETPath = fullfile(pathstr, ['w' name ext]);
        swPETPath = fullfile(pathstr, ['sw' name ext]);
        templatePath = fullfile (cd, 'templates', 'PET.nii');
        spm_normalise(templatePath, PETPath); 
        snPath = fullfile(pathstr, [name '_sn.mat']);
        spm_write_sn(PETPath,snPath);
        %spm_check_registration(char(PETPath, wPETPath));
       
    % Smoothing.
    spm_smooth(wPETPath, swPETPath, 8);
    end
end
end


%==========================================================================
% UTILITY FUNCTIONS
%==========================================================================

% fixed length takes the first N letters of input strings. If the string
% contains less thant N characters, fills with char fillingChar
function strOut = fixedLength(str, N, fillingChar)
    str = upper(str);
    if length(str) > N
        str = str(1:N);
    else
        while length(str) < N
            str = strcat(str,fillingChar);
        end
    end
    strOut = str;
end